package com.compass.mobile.framework.utils

import LogUtil
import android.os.Build.VERSION_CODES.P
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

object PatientDataUtil {

    const val UNDERAGE :Int = 14

    /**
     * 检测是否为有效的身份证号
     */
     fun checkValidIdNumber(idNumber: String):Boolean {
        val pattern = "^\\d{17}[\\d|x|X]{1}$".toRegex()
        return pattern.matches(idNumber)
    }

    /**
     * 根据身份证号码获取到年龄
     */
    fun getAgeByIdNumber(idNumber: String):Int {
        try {
            if(checkValidIdNumber(idNumber)){
                val birthYear = idNumber.substring(6, 14)
                val date:Date =  DateUtils.stringtoDate(birthYear,"yyyyMMdd");
                val currentTime:Long = date.time
                return DateUtils.formatAge2(currentTime)
            }
        }catch (_:Exception){

        }
        return 0
    }

    /**
     * 根据身份证号码获取性别
     */
    fun getSexByIdNumber(idNumber: String):Int{
        var result = 0
        try {
            if(checkValidIdNumber(idNumber)){
              val sex =   idNumber.substring(16,17)
                //1 男 2女
                result =  sex.toInt()%2
//                if( ==0){
//
//                }
//                sex%2
//                info.sex = +idCard.slice(16, 17);
//                info.sex = info.sex % 2 === 0 ? 0 : 1;
            }
        }catch (_:Exception){

        }

        return result;
//        info.sex = +idCard.slice(16, 17);
//        info.sex = info.sex % 2 === 0 ? 0 : 1;
    }
    /**
     * 是否为未成年，未成年的情况下需要校验监护人信息
     */
    fun isUnderage(cardNo:String):Boolean{
        if(checkValidIdNumber(cardNo)){
            return false
        }
        if(getAgeByIdNumber(cardNo) < UNDERAGE){
            return true
        }
        return false
    }

    /**
     * 根据身份证号码获取生日时间戳
     */
    fun getBirthdayByCardNo(cardNo: String):Long{

        var birthday:Long = 0
        if(checkValidIdNumber(cardNo)){
           val dateString  = cardNo.substring(6, 14) // 19001212

            LogUtil.d("截取的年月日：${dateString}")
//            birthday = dateString.toDateLong("yyyyMMdd")
            birthday = DateUtils.stringtoDate(dateString,"yyyyMMdd").time

            LogUtil.d("截取的时间戳：${birthday}")

        }

        return birthday


    }
    fun convertDateStringToTimestamp(dateString: String): Long {
        val dateFormat = SimpleDateFormat("yyyyMMdd", Locale.getDefault())
        val date = dateFormat.parse(dateString)
        return date?.time ?: -1
    }


}